import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:grint/constant/colors.dart';
import 'package:grint/constant/icon_font.dart';
import 'package:grint/utils/whisper.dart';
import 'package:grint/widget/black_button.dart';
import 'package:grint/widget/my_text.dart';
import 'package:grint/widget/report_dialog.dart';
import 'package:video_player/video_player.dart';

class VideoDetailPage extends StatefulWidget {
  final String videoPath;
  final String videoContent;
  final String coverImage;
  final int viewCount;
  final String? videoId; // 添加视频ID用于举报

  const VideoDetailPage({
    super.key,
    required this.videoPath,
    required this.videoContent,
    required this.coverImage,
    this.viewCount = 0,
    this.videoId,
  });

  @override
  State<VideoDetailPage> createState() => _VideoDetailPageState();
}

class _VideoDetailPageState extends State<VideoDetailPage> {
  VideoPlayerController? _controller;
  bool _isPlaying = false;
  bool _isInitialized = false;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _initializeVideo();
  }

  Future<void> _initializeVideo() async {
    try {
      String videoPath = widget.videoPath;
      if (!videoPath.startsWith('assets/')) {
        videoPath = 'assets/$videoPath';
      }

      _controller = VideoPlayerController.asset(videoPath);
      await _controller!.initialize();
      setState(() {
        _isInitialized = true;
        _isLoading = false;
      });
    } catch (e) {
      print('Error initializing video: $e');
      setState(() {
        _isInitialized = false;
        _isLoading = false;
      });
    }
  }

  void _togglePlay() {
    if (_controller != null && _isInitialized) {
      setState(() {
        if (_isPlaying) {
          _controller!.pause();
        } else {
          _controller!.play();
        }
        _isPlaying = !_isPlaying;
      });
    }
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/commonBg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 16.w),
                child: Row(
                  children: [
                    BlackButton(
                      icon: IconFontIcons.iconArrowLeft,
                      onTap: () {
                        context.pop();
                      },
                    ),
                    SizedBox(width: 16.w),
                    Expanded(
                      child: Center(
                        child: MyText(
                          text: 'Tips',
                          type: TextType.rubik,
                          fontSize: 28.sp,
                          fontWeight: FontWeight.bold,
                          color: Colors.black87,
                        ),
                      ),
                    ),
                    BlackButton(
                      icon: IconFontIcons.iconReport2,
                      onTap: () {
                        _showReportDialog();
                      },
                    ),
                    SizedBox(width: 16.w),
                  ],
                ),
              ),

              SizedBox(height: 16.h),

              Padding(
                padding: EdgeInsets.symmetric(horizontal: 16.w),
                child: AspectRatio(
                  aspectRatio: 343 / 682,
                  child: Container(
                    decoration: BoxDecoration(
                      color: AppColors.black,
                      borderRadius: BorderRadius.circular(30.r),
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(18.r),
                      child: Stack(
                        children: [
                          Positioned.fill(
                            child:
                                _isLoading
                                    ? Container(
                                      color: AppColors.black,
                                      child: Center(
                                        child: CircularProgressIndicator(
                                          color: AppColors.white,
                                        ),
                                      ),
                                    )
                                    : _isInitialized && _controller != null
                                    ? VideoPlayer(_controller!)
                                    : Container(
                                      color: AppColors.black,
                                      child: Center(
                                        child: Icon(
                                          Icons.error_outline,
                                          color: AppColors.white,
                                          size: 40.sp,
                                        ),
                                      ),
                                    ),
                          ),

                          Positioned(
                            top: 16.h,
                            left: 16.w,
                            child: Container(
                              padding: EdgeInsets.symmetric(
                                horizontal: 12.w,
                                vertical: 6.h,
                              ),
                              decoration: BoxDecoration(
                                color: AppColors.black.withAlpha(200),
                                borderRadius: BorderRadius.circular(20.r),
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Icon(
                                    Icons.visibility,
                                    color: AppColors.white,
                                    size: 16.sp,
                                  ),
                                  SizedBox(width: 4.w),
                                  MyText(
                                    text: '${widget.viewCount}',
                                    type: TextType.miSans,
                                    fontSize: 14.sp,
                                    color: AppColors.white,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ],
                              ),
                            ),
                          ),

                          // 播放按钮
                          Center(
                            child: GestureDetector(
                              onTap: _togglePlay,
                              child: Icon(
                                IconFontIcons.iconPlayFill,
                                color:
                                    _isPlaying
                                        ? Colors.transparent
                                        : AppColors.white,
                                size: 40.sp,
                              ),
                            ),
                          ),

                          Positioned(
                            bottom: 0.h,
                            left: 0.w,
                            right: 0.w,
                            child: Container(
                              padding: EdgeInsets.symmetric(
                                vertical: 16.w,
                                horizontal: 16.w,
                              ),
                              decoration: BoxDecoration(
                                gradient: LinearGradient(
                                  colors: [
                                    AppColors.black.withAlpha(0),
                                    AppColors.black.withAlpha(150),
                                  ],
                                  begin: Alignment.topCenter,
                                  end: Alignment.bottomCenter,
                                ),
                                borderRadius: BorderRadius.circular(16.r),
                              ),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  MyText(
                                    text: widget.videoContent,
                                    type: TextType.miSans,
                                    fontSize: 14.sp,
                                    color: AppColors.white,
                                    fontWeight: FontWeight.normal,
                                    maxLines: 4,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ),

              SizedBox(height: 20.h),
            ],
          ),
        ),
      ),
    );
  }

  void _showReportDialog() {
    FankuiTanchuangBangzhu.xianshi(
      context,
      mubiaoNeirongId: widget.videoId ?? widget.videoPath,
      onJubao: (jubaoLeixing, fujiaxinxi) {
        _handleVideoReport(jubaoLeixing, fujiaxinxi);
      },
    );
  }

  void _handleVideoReport(JubaoLeixing jubaoLeixing, String? fujiaxinxi) {
    Future.delayed(Duration(seconds: 1), () {
      if (mounted) {
        _deleteVideoAndReturnHome();
      }
    });
  }

  void _deleteVideoAndReturnHome() {
    if (mounted) {
      context.pop({
        'action': 'delete_video',
        'videoPath': widget.videoPath,
        'videoId': widget.videoId,
      });
    }
  }
}
